"""
对坐标点集进行平滑处理
"""
import math
import numpy as np


# 利用n阶贝塞尔曲线平滑处理
def Bezier(points, n):
    smoothed_points = []

    return smoothed_points


# n阶贝塞尔曲线，全局平滑结果
def binomialCoefficientIterative(n, k):
    if k < 0 or k > n:
        return 0
    result = 1
    for i in range(1, k + 1):
        result = result * (n - i + 1) / i

    return result


# 获取n阶贝塞尔曲线
def getBezierCurvePointN(number_of_points, points):
    n = len(points) - 1
    bezier_points = []
    interval = 1 / number_of_points
    # 获取平滑处理后的坐标
    for t in np.arange(0, 1, interval):
        # 生成n阶贝塞尔曲线
        x = 0
        y = 0
        for i in range(0, n + 1):
            point = points[i]
            binomial_coefficient = binomialCoefficientIterative(n, i)
            x += binomial_coefficient * math.pow(1 - t, n - i) * math.pow(t, i) * point[0]
            y += binomial_coefficient * math.pow(1 - t, n - i) * math.pow(t, i) * point[1]
        bezier_points.append((x, y))
    # 处理终点
    if bezier_points[-1] != points[-1]:
        bezier_points.append(points[-1])

    return bezier_points


# 平滑处理
def smoothPointSet(number_of_points, points, auto_len=False):
    n = len(points)
    if number_of_points < 0:
        number_of_points = n
    else:
        # 若点集本身长度小于number_of_points， 则number_of_points等于点集长度
        if auto_len:
            number_of_points = n if n < number_of_points else number_of_points
    smoothed_points = getBezierCurvePointN(number_of_points, points)
    return smoothed_points
